package com.zx._12_算法.应用.限流;

import java.util.Calendar;
import java.util.Date;
import java.util.Random;

public class CounterLimit {

    // 记录上次统计时间
    static Date lastDate = new Date();
    // 初始化值
    static int counter = 0;

    // 限流方法
    static boolean countLimit() {
        // 获取当前时间
        Date now = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(now);
        // 当前分
        int minute = calendar.get(Calendar.MINUTE);
        calendar.setTime(lastDate);
        int lastMinute = calendar.get(Calendar.MINUTE);
        if (minute != lastMinute) {
            lastDate = now;
            counter = 0;
        }
        ++counter;
        return counter >= 100; // 判断计数器是否大于每分钟限定的值。
    }

    // 测试方法
    public static void main(String[] args) {
        for (; ; ) {
            // 模拟一秒
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Random random = new Random();
            int i = random.nextInt(3);
            // 模拟1秒内请求1次
            if (i == 1) {
                if (countLimit()) {
                    System.out.println("限流了" + counter);

                } else {
                    System.out.println("没限流" + counter);
                }
            } else if (i == 2) { // 模拟1秒内请求2次
                for (int j = 0; j < 2; j++) {
                    if (countLimit()) {
                        System.out.println("限流了" + counter);
                    } else {
                        System.out.println("没限流" + counter);
                    }
                }
            } else { // 模拟1秒内请求10次
                for (int j = 0; j < 10; j++) {
                    if (countLimit()) {
                        System.out.println("限流了" + counter);
                    } else {
                        System.out.println("没限流" + counter);
                    }
                }
            }
        }
    }
}
